package edu.tjpu.share.newui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.task.UserModifyTask;
import edu.tjpu.share.util.BitMapDrawableUtil;
import edu.tjpu.share.util.BitapCompress;
import edu.tjpu.share.util.FileUtil;

public class SelectAvatar extends Activity {
	private ImageView add_avatar_view;
	private Button btn_motakephoto,btn_mochoosepic,btn_goodtogo;
	
	Uri imageuri;
	String img_path;
	private String newImgPath;
	private UserVo user;
	private Server serverinfo;
	
	ProgressDialog pd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.modify_user_layout);
		
		java.io.File cache = SelectAvatar.this.getCacheDir();
		java.io.File cacheServerinfoFile = new java.io.File(cache,
				Fields.SERVER_INFO);
		java.io.File cacheUserFile = new java.io.File(cache, Fields.USER);
		user = (UserVo) FileUtil.ReadObjectFromFile(cacheUserFile
				.getAbsolutePath());
		serverinfo = (Server) FileUtil
				.ReadObjectFromFile(cacheServerinfoFile.getAbsolutePath());
		
		add_avatar_view = (ImageView) findViewById(R.id.add_avatar_view);
		btn_motakephoto = (Button) findViewById(R.id.btn_motakephoto);
		btn_mochoosepic = (Button) findViewById(R.id.btn_mochoosepic);
		btn_goodtogo = (Button) findViewById(R.id.btn_goodtogo);
		
		
		btn_goodtogo.setOnClickListener(new View.OnClickListener() {
			
			@SuppressWarnings("unchecked")
			public void onClick(View v) {
				
				if(user.getUavatar()!=null){
					pd = ProgressDialog.show(SelectAvatar.this, "请稍等...",
							"正在连接服务器...", true);

					HashMap<String, Object> params = new HashMap<String, Object>();

					params.put(Fields.SERVER_INFO, serverinfo);
					params.put(Fields.USER, user);
					params.put(Fields.HANDLER, handler);
					params.put(Fields.IMAGE_UNSPECIFIED, true);
					
					new UserModifyTask().execute(params);
				}
				
			}
		});
		
		btn_mochoosepic.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
				// 查看类型 String, IMAGE_UNSPECIFIED, "image/*";
				innerIntent.setType(Fields.IMAGE_UNSPECIFIED);
				Intent wrapperIntent = Intent
						.createChooser(innerIntent, "选择图片");
				((Activity) SelectAvatar.this).startActivityForResult(
						wrapperIntent, Fields.ACTIVITY_GET_IMAGE);
				wrapperIntent.putExtra("return-data", true);
			}
		});

		btn_motakephoto.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				if (checkSoftStage()) {

					String fileName = System.currentTimeMillis() + ".jpg";
					String imgPath = "/sdcard/share/pic";
					File newFile = new File(imgPath);
					if (!newFile.exists()) {
						newFile.mkdirs();
					}

					newImgPath = imgPath + "/" + fileName;

					Intent it = new Intent("android.media.action.IMAGE_CAPTURE");
					it.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(newFile, fileName)));
					startActivityForResult(it, Fields.TAKE_PICTURE);
				}
			}
		});
	}
	
	/**
	 * 检测手机是否存在SD卡,网络连接是否打开
	 */
	private boolean checkSoftStage() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { // 判断是否存在SD卡
			return true;
		} else {
			new AlertDialog.Builder(this)
					.setMessage("检测到手机没有存储卡！请插入手机存储卡再使用本功能。")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
								}
							}).show();
			return false;
		}
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			add_avatar_view.setVisibility(View.VISIBLE);
			if (requestCode == Fields.ACTIVITY_GET_IMAGE) {
				imageuri = data.getData();

				if(imageuri.toString().contains("file:///")){
					try {
						img_path=URLDecoder.decode(imageuri.toString(),"UTF-8").substring(7);
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}else{
				String[] proj = { MediaStore.Images.Media.DATA };
  
				Cursor actualimagecursor = managedQuery(imageuri, proj, null,
						null, null);

				int actual_image_column_index = actualimagecursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

				actualimagecursor.moveToFirst();

				img_path = actualimagecursor
						.getString(actual_image_column_index);
				}
				img_path = BitapCompress.GetImageBitmap(img_path);
				File file = new File(img_path);
				FileInputStream fis;
				try {
					fis = new FileInputStream(file);
					byte[] b = new byte[Long.valueOf(file.length()).intValue()];
					fis.read(b);

					add_avatar_view.setScaleType(ImageView.ScaleType.CENTER);
					add_avatar_view.setImageBitmap(BitMapDrawableUtil.getBitmapFromByte(b));
					
					user.setUavatar(b);
					user.setXmppUsername(file.getAbsolutePath());
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
			if (requestCode == Fields.TAKE_PICTURE) {
				newImgPath = BitapCompress.GetImageBitmap(newImgPath);
				File file = new File(newImgPath);
				FileInputStream fis;
				try {
					fis = new FileInputStream(file);
					byte[] b = new byte[(int) file.length()];
					fis.read(b);
					
					add_avatar_view.setScaleType(ImageView.ScaleType.CENTER);
					add_avatar_view.setImageBitmap(BitMapDrawableUtil.getBitmapFromByte(b));
					
					user.setUavatar(b);
					user.setXmppUsername(file.getAbsolutePath());
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Fields.SUCCESS) {
				if (pd != null)
					pd.dismiss();
				Toast.makeText(getApplicationContext(), "修改成功！",
						Toast.LENGTH_SHORT).show();
				Intent intent = new Intent();
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.setClass(getApplicationContext(), MainTabHost.class);
				startActivity(intent);
				finish();
			}else{
				if (pd != null)
					pd.dismiss();
				Toast.makeText(getApplicationContext(), "修改失败！",
						Toast.LENGTH_SHORT).show();
			}
			super.handleMessage(msg);
		}
	};

}
